package com.swe727.spring2011.constraint1.server;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import com.swe727.spring2011.constraint1.client.util.LogUtil;
import com.swe727.spring2011.constraint1.node.NodeDataStore;
import com.swe727.spring2011.constraint1.observation.ObservationDataStore;

public class ZoneServer {

	public static final String SAVE_OBSERVATION_ID = "saveObservation";
	public static final String GET_OBSERVATION_ID = "getObservation";
	public static final String REGISTER_ID = "register";
	public static final String MEDEVAC_ID = "medevac";
	
	public static void main(String[] args) throws NumberFormatException, RemoteException, InterruptedException {
		if (args.length != 2) {
			System.out.println("Usage: ZoneServer <port> <rootDir> \nwhere port is the port number of the RMI registry.");
			System.exit(1);
		}
		
		LogUtil.ROOT_DIR = args[1];
		
		System.out.println("ZoneServer running on port "+args[0]+". May the force be with you.....");
		
		Registry registry = LocateRegistry.createRegistry(Integer.parseInt(args[0]));
		
		// initialize the data stores
		ObservationDataStore obsStore = ObservationDataStore.getStore();
		NodeDataStore.getStore();
		
		SaveObservationHandler saveObs = new SaveObservationHandler(obsStore);
		GetObservationHandler getObs = new GetObservationHandler(obsStore);
		RegisterNodeHandler regNode = new RegisterNodeHandler();
		ServerMedevacHandler med = new ServerMedevacHandler();
		
		SaveObservationRemote saveObsStub = (SaveObservationRemote) UnicastRemoteObject.exportObject(saveObs, 0);
		GetObservationRemote getObsStub = (GetObservationRemote) UnicastRemoteObject.exportObject(getObs, 0);
		RegisterNodeRemote regNodeStub = (RegisterNodeRemote) UnicastRemoteObject.exportObject(regNode, 0);
		ServerMedevacRemote medStub = (ServerMedevacRemote) UnicastRemoteObject.exportObject(med, 0);
		
        registry.rebind(SAVE_OBSERVATION_ID, saveObsStub);
        registry.rebind(GET_OBSERVATION_ID, getObsStub);
        registry.rebind(REGISTER_ID, regNodeStub);
        registry.rebind(MEDEVAC_ID, medStub);
        
        while (true) {
        	LogUtil.writeMemoryUsage("zone-server");
        	Thread.sleep(10000);
        }
	}
}
